import os
import pathlib

import pdfplumber
from PIL import Image


def covert2pic(pdf_path, png_path):
    if pdf_path is None:
        raise 'pdf_path必传'
    if png_path is None:
        png_path = pdf_path
    with pdfplumber.open(pdf_path) as pdf:
        for i, page in enumerate(pdf.pages):
            im = page.to_image(resolution=200)
            save = os.path.join(png_path, '%s.png' % (int(i) + 1))
            im.save(save)
            print('----分割线,第%d页----' % (int(i) + 1))


def merge_images(images, output_path):
    if len(images) > 0:
        first_images = Image.open(images[0])
        width, height = first_images.size
        merged_image = Image.new('RGB', (width, height * len(images)))
        for i, image_path in enumerate(images):
            image = Image.open(image_path)
            merged_image.paste(image, (0, i * height))
        merged_image.save(output_path)


def test():
    # covert2pic('/Users/banla/Downloads/京东安联-商业险.pdf', '/Users/banla/Downloads/')
    os.system('rm -rf /Users/banla/Downloads/test.png')
    list = [path for path in pathlib.Path('/Users/banla/Downloads/').glob(r'*.png')][::-1]
    merge_images(list, '/Users/banla/Downloads/test.png')


if __name__ == '__main__':
    test()
